package zhongbo.java.air.monitor.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import zhongbo.java.air.common.vo.PageVo;
import zhongbo.java.air.monitor.mapper.AirAlertLogMapper;
import zhongbo.java.air.monitor.model.AirAlertLog;
import zhongbo.java.air.monitor.service.IAirAlertLogService;
import zhongbo.java.air.monitor.service.IJtsService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class IAirAlertLogServiceImpl implements IAirAlertLogService<AirAlertLog> {
    @Autowired
    private IJtsService jtsService;

    @Autowired
    private AirAlertLogMapper airAlertLogMapper;

    @Autowired
    private ObjectMapper objectMapper; // 新增：注入 ObjectMapper

//    @Override
//    public AirAlertLog update(AirAlertLog airAlertLog) {
//        if (airAlertLog == null){
//            throw new RuntimeException("更新失败");
//        }
//        // 新增：验证和格式化 triggerCoordinates
//        try {
//            airAlertLog.setTriggerCoordinates(objectMapper.writeValueAsString(airAlertLog.getTriggerCoordinates())); // 修改：序列化 triggerCoordinates
//        } catch (Exception e) {
//            throw new RuntimeException("triggerCoordinates 序列化失败", e);
//        }
//        int update = airAlertLogMapper.updateById(airAlertLog);
//        if (update > 0){
//            return airAlertLog;
//        }
//        return null;
//    }
@Override
public AirAlertLog edit(AirAlertLog edit) {
    if (edit == null){
        throw new RuntimeException("更新失败");
    }
    // 新增：验证和格式化 triggerCoordinates
    try {
        edit.setTriggerCoordinates(objectMapper.writeValueAsString(edit.getTriggerCoordinates())); // 修改：序列化 triggerCoordinates
    } catch (Exception e) {
        throw new RuntimeException("triggerCoordinates 序列化失败", e);
    }
    int update = airAlertLogMapper.updateById(edit);
    if (update > 0){
        return edit;
    }
    return null;
}

//    @Override
//    public AirAlertLog insert(AirAlertLog airAlertLog) {
//        if (airAlertLog == null){
//            throw new RuntimeException("新增失败");
//        }
//        // 新增：验证和格式化 triggerCoordinates
//        try {
//            airAlertLog.setTriggerCoordinates(objectMapper.writeValueAsString(airAlertLog.getTriggerCoordinates())); // 修改：序列化 triggerCoordinates
//        } catch (Exception e) {
//            throw new RuntimeException("triggerCoordinates 序列化失败", e);
//        }
//        int insert = airAlertLogMapper.insert(airAlertLog);
//        if (insert > 0){
//            return airAlertLog;
//        }
//        return null;
//    }
@Override
public AirAlertLog add(AirAlertLog entity) {
    if (entity == null){
        throw new RuntimeException("新增失败");
    }
    // 新增：验证和格式化 triggerCoordinates
    try {
        entity.setTriggerCoordinates(objectMapper.writeValueAsString(entity.getTriggerCoordinates())); // 修改：序列化 triggerCoordinates
    } catch (Exception e) {
        throw new RuntimeException("triggerCoordinates 序列化失败", e);
    }
    int insert = airAlertLogMapper.insert(entity);
    if (insert > 0){
        return entity;
    }
    return null;
}

//    @Override
//    public boolean deleteById(String id) {
//        if (id == null){
//            throw new RuntimeException("id不能为空");
//        }
//        log.info("删除ID为 {} 的飞行活动记录", id);
//        int delete = airAlertLogMapper.deleteById(id);
//        if (delete == 0){
//            throw new RuntimeException("删除失败");
//        }
//        return delete > 0;
//    }
@Override
public boolean delete(String entityId) {
    if (entityId == null){
        throw new RuntimeException("id不能为空");
    }
    log.info("删除ID为 {} 的飞行活动记录", entityId);
    int delete = airAlertLogMapper.deleteById(entityId);
    if (delete == 0){
        throw new RuntimeException("删除失败");
    }
    return delete > 0;
}

    /**
     * 根据ID查询告警日志记录
     * 适用场景：需要查看某一条具体的告警日志记录时使用
     *
     * @param entityId 告警日志记录ID
     * @return 告警日志记录
     */
//    @Override
//    public AirAlertLog queryById(String id) {
//        if (id == null){
//            throw new RuntimeException("id不能为空");
//        }
//        log.info("查询ID为 {} 的飞行活动记录", id);
//        if (airAlertLogMapper.selectById(id) == null){
//            throw new RuntimeException("id不存在");
//        }
//        return airAlertLogMapper.selectById(id);
//    }
    @Override
    public AirAlertLog findOne(String entityId) {
        if (entityId == null){
            throw new RuntimeException("id不能为空");
        }
        log.info("查询ID为 {} 的飞行活动记录", entityId);
        if (airAlertLogMapper.selectById(entityId) == null){
            throw new RuntimeException("id不存在");
        }
        return airAlertLogMapper.selectById(entityId);
    }


    @Override
    public PageVo<AirAlertLog> findPage(int page, int pageSize, String keyword, String fields, String oderByField, boolean orderByAsc) {
        QueryWrapper<AirAlertLog> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(keyword) && StrUtil.isNotBlank(fields)) {
            String[] fieldsArray = fields.split(",");
            for (String field : fieldsArray) {
                queryWrapper.or().like(StrUtil.toUnderlineCase(field),keyword);
            }
        }
        IPage<AirAlertLog> pageParam = new Page<>(page, pageSize);
        IPage airAlertZoneIPage = airAlertLogMapper.selectPage(pageParam,queryWrapper);
        return new PageVo<>(airAlertZoneIPage);
    }
    /**
     * 查询指定ICAO代码和触发时间之后的告警日志记录
     * 适用场景：需要查看某架飞机在某个时间点之后的告警日志记录时使用
     *
     * @param icaoCode    ICAO代码
     * @param triggerTime 触发时间
     * @return 告警日志记录列表
     */
    @Override
    public AirAlertLog queryRecentAlerts(String icaoCode, Date triggerTime) throws RuntimeException{
        if (icaoCode == null || triggerTime == null) {
            throw new RuntimeException("ICAO代码和触发时间不能为空");
        }
        QueryWrapper<AirAlertLog> queryWrapper = new QueryWrapper();
        queryWrapper.eq("icao_code",icaoCode);
        // 查询5分钟内 triggerTime
        queryWrapper.between("trigger_time",new Date(triggerTime.getTime() - 5 * 60 * 1000),triggerTime);
        try {
            AirAlertLog airAlertLog = airAlertLogMapper.selectOne(queryWrapper);
            return airAlertLog;
        }catch (RuntimeException e){
            throw new RuntimeException("查询失败 ->>> icaoCode：" + icaoCode + " triggerTime：" + triggerTime);
        }
    }
        


    /**
     * 手动查询告警日志记录
     * 适用场景：根据指定的条件查询告警日志记录
     *
     * @param alertType 告警类型（可选）
     * @param status 处理状态（可选）
     * @param startTime 开始时间（可选）
     * @param endTime 结束时间（可选）
     * @return 告警日志记录列表
     */
    @Override
    public List<AirAlertLog> queryManualAlerts(String alertType, String status, String startTime, String endTime) {
        QueryWrapper<AirAlertLog> queryWrapper = new QueryWrapper<>();
        
        if (alertType != null) {
            queryWrapper.eq("alert_type", alertType);
        }
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        if (startTime != null && endTime != null) {
            queryWrapper.between("trigger_time", parseDate(startTime), parseDate(endTime));
        } else if (startTime != null) {
            queryWrapper.ge("trigger_time", parseDate(startTime));
        } else if (endTime != null) {
            queryWrapper.le("trigger_time", parseDate(endTime));
        }
        
        queryWrapper.orderByDesc("trigger_time");
        
        List<AirAlertLog> manualAlerts = airAlertLogMapper.selectList(queryWrapper);
        
        if (manualAlerts == null || manualAlerts.isEmpty()) {
            throw new RuntimeException("未找到符合条件的告警日志记录");
        }
        
        return manualAlerts;
    }

    private Date parseDate(String dateStr) {
        try {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").parse(dateStr);
        } catch (ParseException e) {
            throw new IllegalArgumentException("日期格式不正确", e);
        }
    }
}